package com.cjk.foundation.dao;

import java.util.Date;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.cjk.foundation.entity.TunnelEntity;
import com.cjk.foundation.enums.TunnelStatus;

@Repository
public interface TunnelDao {

	public void insert(TunnelEntity tunnelEntity);

	public List<TunnelEntity> selectListByCondition(@Param("sn") String sn, @Param("userId") Integer userId, @Param("status") TunnelStatus status, @Param("page") Integer page,
			@Param("pageSize") Integer pageSize);

	public Integer selectCountByCondition(@Param("sn") String sn, @Param("userId") Integer userId, @Param("status") TunnelStatus status);

	@ResultMap("resultMap")
	@Select("select * from tunnel where id = #{id}")
	public TunnelEntity selectById(@Param("id") Integer id);
	
	@ResultMap("resultMap")
	@Select("select * from tunnel where remote_client = #{sn} and remote_port = #{remotePort} and tunnel_status = #{status}")
	public TunnelEntity selectByCondition(@Param("sn") String sn, @Param("remotePort") Integer remotePort, @Param("status") TunnelStatus status);

	@Update("update tunnel set finish_time = #{finishTime}, tunnel_status = #{status}, fail_code = #{failCode}, fail_msg = #{failMsg}, create_success = #{createSuccess} where id = #{id}")
	public void createComplete(@Param("finishTime") Date finishTime, @Param("status") TunnelStatus status,
			@Param("failCode") Integer failCode, @Param("failMsg") String failMsg,
			@Param("createSuccess") String createSuccess, @Param("id") Integer id);
	
	@Update("update tunnel set tunnel_status = #{status} where id = #{id}")
	public void updateStatus(@Param("id") Integer id, @Param("status") TunnelStatus status);
	
	@Select("SELECT local_port FROM `tunnel` where tunnel_status = 'ESTABLISHED' order by local_port desc LIMIT 0, 1")
	public Integer selectMaxPortInUsed();
}
